'use client'

import { useState, useEffect } from 'react'
import { trpc } from '@/lib/trpc-provider'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Copy, RotateCcw, Clock, Calendar } from 'lucide-react'
import { toast } from 'sonner'

type TimestampFormat = 'timestamp' | 'datetime' | 'iso' | 'relative'

export default function TimestampConverterPage() {
  const [input, setInput] = useState('')
  const [fromFormat, setFromFormat] = useState<'timestamp' | 'datetime'>('timestamp')
  const [currentTime, setCurrentTime] = useState(new Date())
  const [results, setResults] = useState<{
    timestamp: number | null
    timestampMs: number | null
    datetime: string | null
    iso: string | null
    relative: string | null
  }>({ timestamp: null, timestampMs: null, datetime: null, iso: null, relative: null })

  // 更新当前时间
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date())
    }, 1000)
    return () => clearInterval(timer)
  }, [])

  const convertTimestamp = trpc.tools.convertTimestamp.useMutation({
    onSuccess: (data) => {
      if (data.success) {
        setResults({
          timestamp: data.timestamp,
          timestampMs: data.timestampMs,
          datetime: data.datetime,
          iso: data.iso,
          relative: null // 相对时间需要单独计算
        })
        
        // 计算相对时间
        if (data.timestampMs) {
          const now = new Date()
          const diff = now.getTime() - data.timestampMs
          const seconds = Math.floor(diff / 1000)
          const minutes = Math.floor(seconds / 60)
          const hours = Math.floor(minutes / 60)
          const days = Math.floor(hours / 24)
          
          let relative: string
          if (Math.abs(days) > 0) {
            relative = days > 0 ? `${days}天前` : `${Math.abs(days)}天后`
          } else if (Math.abs(hours) > 0) {
            relative = hours > 0 ? `${hours}小时前` : `${Math.abs(hours)}小时后`
          } else if (Math.abs(minutes) > 0) {
            relative = minutes > 0 ? `${minutes}分钟前` : `${Math.abs(minutes)}分钟后`
          } else if (Math.abs(seconds) > 0) {
            relative = seconds > 0 ? `${seconds}秒前` : `${Math.abs(seconds)}秒后`
          } else {
            relative = '刚刚'
          }
          
          setResults(prev => ({ ...prev, relative }))
        }
      } else {
        toast.error(data.error || '时间戳转换失败')
      }
    },
    onError: (error) => {
      toast.error(error.message || '时间戳转换失败')
    }
  })

  const handleConvert = () => {
    if (!input.trim()) {
      toast.error('请输入要转换的时间')
      return
    }

    convertTimestamp.mutate({
      input: input.trim(),
      fromFormat,
      toFormat: 'datetime' // 我们总是转换为datetime来获取所有格式
    })
  }

  const handleCopy = async (text: string, format: string) => {
    try {
      await navigator.clipboard.writeText(text)
      toast.success(`${format}已复制到剪贴板`)
    } catch (error) {
      toast.error('复制失败')
    }
  }

  const handleClear = () => {
    setInput('')
    setResults({ timestamp: null, timestampMs: null, datetime: null, iso: null, relative: null })
  }

  const handleCurrentTime = () => {
    const now = new Date()
    if (fromFormat === 'timestamp') {
      setInput(Math.floor(now.getTime() / 1000).toString())
    } else {
      setInput(now.toLocaleString('zh-CN'))
    }
  }

  const quickTimestamps = [
    {
      name: '当前时间',
      timestamp: Math.floor(Date.now() / 1000),
      description: '现在'
    },
    {
      name: '1小时前',
      timestamp: Math.floor((Date.now() - 3600000) / 1000),
      description: '一小时前'
    },
    {
      name: '1天前',
      timestamp: Math.floor((Date.now() - 86400000) / 1000),
      description: '昨天此时'
    },
    {
      name: '1周前',
      timestamp: Math.floor((Date.now() - 604800000) / 1000),
      description: '一周前'
    },
    {
      name: '1个月前',
      timestamp: Math.floor((Date.now() - 2592000000) / 1000),
      description: '一个月前'
    },
    {
      name: 'Unix纪元',
      timestamp: 0,
      description: '1970-01-01 00:00:00'
    }
  ]

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-3xl font-bold mb-2">时间戳转换工具</h1>
          <p className="text-muted-foreground">
            在时间戳和日期时间之间进行转换，支持多种时间格式
          </p>
        </div>

        <div className="grid gap-6">
          {/* 当前时间显示 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Clock className="w-5 h-5" />
                当前时间
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div>
                  <Label className="text-muted-foreground">时间戳 (秒)</Label>
                  <p className="font-mono text-lg">{Math.floor(currentTime.getTime() / 1000)}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">日期时间</Label>
                  <p className="font-mono text-lg">{currentTime.toLocaleString('zh-CN')}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">时间戳 (毫秒)</Label>
                  <p className="font-mono">{currentTime.getTime()}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">ISO格式</Label>
                  <p className="font-mono">{currentTime.toISOString()}</p>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 输入区域 */}
          <Card>
            <CardHeader>
              <CardTitle>时间转换</CardTitle>
              <CardDescription>
                输入要转换的时间戳或日期时间
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="md:col-span-2">
                    <Label htmlFor="time-input">时间值</Label>
                    <Input
                      id="time-input"
                      value={input}
                      onChange={(e) => setInput(e.target.value)}
                      placeholder={fromFormat === 'timestamp' ? '输入时间戳...' : '输入日期时间...'}
                      className="font-mono"
                    />
                  </div>
                  <div>
                    <Label htmlFor="from-format">输入格式</Label>
                    <Select value={fromFormat} onValueChange={(value) => setFromFormat(value as 'timestamp' | 'datetime')}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="timestamp">时间戳</SelectItem>
                        <SelectItem value="datetime">日期时间</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                <div className="flex flex-wrap gap-2">
                  <Button
                    onClick={handleConvert}
                    disabled={convertTimestamp.isPending}
                  >
                    <Calendar className="w-4 h-4 mr-2" />
                    转换时间
                  </Button>
                  <Button variant="outline" onClick={handleCurrentTime}>
                    <Clock className="w-4 h-4 mr-2" />
                    当前时间
                  </Button>
                  <Button variant="outline" onClick={handleClear}>
                    <RotateCcw className="w-4 h-4 mr-2" />
                    清空
                  </Button>
                </div>
                
                {/* 格式示例 */}
                <div>
                  <Label className="text-sm font-medium">格式示例：</Label>
                  <div className="mt-2 text-sm text-muted-foreground">
                    {fromFormat === 'timestamp' ? (
                      <div className="space-y-1">
                        <p><code className="bg-muted px-1 py-0.5 rounded">1640995200</code> - 10位秒级时间戳</p>
                        <p><code className="bg-muted px-1 py-0.5 rounded">1640995200000</code> - 13位毫秒级时间戳</p>
                      </div>
                    ) : (
                      <div className="space-y-1">
                        <p><code className="bg-muted px-1 py-0.5 rounded">2024-01-01 12:00:00</code></p>
                        <p><code className="bg-muted px-1 py-0.5 rounded">2024/01/01 12:00:00</code></p>
                        <p><code className="bg-muted px-1 py-0.5 rounded">2024-01-01T12:00:00Z</code></p>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 快速时间戳 */}
          <Card>
            <CardHeader>
              <CardTitle>快速时间戳</CardTitle>
              <CardDescription>
                点击选择常用时间戳
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                {quickTimestamps.map((item, index) => (
                  <button
                    key={index}
                    onClick={() => {
                      setInput(item.timestamp.toString())
                      setFromFormat('timestamp')
                    }}
                    className="p-3 text-left border rounded-lg hover:bg-muted/50 transition-colors"
                  >
                    <div className="font-medium">{item.name}</div>
                    <div className="text-sm text-muted-foreground">{item.description}</div>
                    <div className="text-xs font-mono mt-1">{item.timestamp}</div>
                  </button>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* 转换结果 */}
          {(results.timestamp || results.datetime) && (
            <Card>
              <CardHeader>
                <CardTitle>转换结果</CardTitle>
                <CardDescription>
                  所有格式的时间表示
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {results.timestamp && (
                    <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <Label className="text-sm font-medium">时间戳 (秒)</Label>
                        <p className="font-mono">{results.timestamp}</p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(results.timestamp!.toString(), '时间戳')}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                  
                  {results.timestampMs && (
                    <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <Label className="text-sm font-medium">时间戳 (毫秒)</Label>
                        <p className="font-mono">{results.timestampMs}</p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(results.timestampMs!.toString(), '毫秒时间戳')}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                  
                  {results.datetime && (
                    <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <Label className="text-sm font-medium">日期时间</Label>
                        <p className="font-mono">{results.datetime}</p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(results.datetime!, '日期时间')}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                  
                  {results.iso && (
                    <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <Label className="text-sm font-medium">ISO格式</Label>
                        <p className="font-mono text-sm">{results.iso}</p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(results.iso!, 'ISO格式')}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                  
                  {results.relative && (
                    <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                      <div>
                        <Label className="text-sm font-medium">相对时间</Label>
                        <p className="font-mono">{results.relative}</p>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleCopy(results.relative!, '相对时间')}
                      >
                        <Copy className="w-4 h-4" />
                      </Button>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {/* 使用说明 */}
          <Card>
            <CardHeader>
              <CardTitle>使用说明</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4 text-sm">
                <div>
                  <h4 className="font-medium mb-2">支持的时间格式：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li><strong>时间戳</strong>: 10位秒级或13位毫秒级Unix时间戳</li>
                    <li><strong>日期时间</strong>: 标准日期时间格式，如 2024-01-01 12:00:00</li>
                    <li><strong>ISO格式</strong>: 国际标准时间格式，如 2024-01-01T12:00:00.000Z</li>
                    <li><strong>相对时间</strong>: 相对于当前时间的描述，如 "3小时前"</li>
                  </ul>
                </div>
                <div>
                  <h4 className="font-medium mb-2">使用技巧：</h4>
                  <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                    <li>自动识别10位秒级和13位毫秒级时间戳</li>
                    <li>支持多种日期时间输入格式</li>
                    <li>实时显示当前时间的各种格式</li>
                    <li>提供常用时间戳的快速选择</li>
                    <li>一键复制任意格式的转换结果</li>
                  </ul>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  )
}